<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Install 安装向导</title>
    <link href="static/css/bootstrap-icons.css" rel="stylesheet">
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <link href="static/css/vui365.css" rel="stylesheet">
    <style>
        html {
            color: #333;
            font-size: 14px;
        }

        h4 {
            font-size: 18px;
            margin: 15px 0;
        }

        table td:first-child {
            text-align: right;
        }

        table td:nth-child(3) {
            color: #9A9A9A !important
        }

        .log-list {
            font-size: 12px;
            color: #555;
        }
    </style>
</head>

<body>
    <div id="app" class="d-flex flex-column" v-cloak>
        <header>
            <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Admin 安装向导</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                        aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                </div>
            </nav>
        </header>
        <main class="flex-grow-1 border-top border-bottom border-primary border-2 px-3">
            <div class="my-1" style="height:calc(100vh - 125px); overflow-y: auto;">
                <div>
                    <h4>填写数据库信息</h4>
                    <table>
                        <tbody>
                            <tr>
                                <td>服务器：</td>
                                <td><input type="search" class="form-control form-control-sm" v-model="dbcfg.host"></td>
                                <td>数据库服务器地址, 一般为 localhost</td>
                            </tr>
                            <tr>
                                <td>端口号：</td>
                                <td><input type="search" class="form-control form-control-sm" v-model="dbcfg.port"></td>
                                <td>数据库端口号, 一般为 3306</td>
                            </tr>
                            <tr>
                                <td>数据库名称：</td>
                                <td>
                                    <input type="search" class="form-control form-control-sm" v-model="dbcfg.database">
                                </td>
                                <td>数据库的名称。<a href="#" @click.prevent="checkDbExists()" class="mx-1">[检测]</a>
                                    <span v-show="dbStatus==0" class="text-muted">
                                        数据库不存在，请先手动创建或
                                        <a class="mx-1" @click="onCreateDatabase">尝试创建</a>
                                    </span>
                                    <span v-show="dbStatus==1" class="text-success">数据库已存在</span>
                                </td>
                            </tr>
                            <tr>
                                <td>用户名：</td>
                                <td><input type="search" class="form-control form-control-sm" v-model="dbcfg.user"></td>
                                <td>&nbsp;</td>
                            </tr>
                            <tr>
                                <td>密码：</td>
                                <td><input type="password" class="form-control form-control-sm"
                                        v-model="dbcfg.password"></td>
                                <td>&nbsp;</td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td><button class="btn btn-sm btn-secondary mx-0"
                                        @click.stop="onTestConnection">测试连接</button></td>
                                <td>&nbsp;</td>
                            </tr>
                        </tbody>
                    </table>
                    <h4>填写管理员信息</h4>
                    <table>
                        <tbody>
                            <tr>
                                <td>管理员账号：</td>
                                <td><input type="search" class="form-control form-control-sm"
                                        v-model="dbcfg.admin_account"></td>
                                <td>6-10个字符，只限英文字母和下划线，不能包含中文、其它字符等</td>
                            </tr>
                            <tr>
                                <td>管理员密码：</td>
                                <td><input type="password" class="form-control form-control-sm"
                                        v-model="dbcfg.admin_password"></td>
                                <td>8-16个字符，只限英文字母和下划线、@符号、#符号，不能包含中文和其它字符</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div v-if="dataOfLog.length>0">
                    <h4>执行信息 <small>({{installStep+'/'+dataOfLog.length}})</small></h4>
                    <div class="container-fluid log-list" style="max-height:400px; overflow-y:auto">
                        <div v-for="(item,idx) of dataOfLog" class="row py-2 border-bottom">
                            <div :class="'col-6'+(item.status>0? ' text-muted' : '')">{{idx+1}}. {{item.text}}</div>
                            <div class="col-6 text-end">
                                <div v-if="item.status==1" class="text-success">
                                    成功
                                </div>
                                <div v-if="item.status==2" class="text-danger">
                                    <span>失败</span>
                                    <div style="max-height:50px; overflow-y:auto">{{item.error}}</div>
                                </div>
                                <div v-if="item.status==0">待安装</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <footer class="d-flex justify-content-between my-3 px-3">
            <div class="copyright mt-2">© 2021 <a href="https://gitee.com/sochishun/tvadmin" target="_blank"
                    class="text-reset">TvAdmin</a></div>
            <div>
                <a class="btn btn-outline-secondary me-2" href="index.html">返回</a>
                <button class="btn btn-primary" @click.prevent="onInstall()">
                    <div v-if="loadingState.install" class="spinner-border  spinner-border-sm" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    开始安装
                </button>
            </div>
        </footer>
    </div>
    <script src="static/js/bootstrap.bundle.min.js"></script>
    <script src="static/js/vue.global.prod.min.js"></script>
    <script src="static/js/axios.min.js"></script>
    <script src="static/js/vui365.js"></script>
    <script>
        // 应用配置
        const App = {
            data() {
                return {
                    dbcfg: {
                        host: 'localhost',
                        port: '3306',
                        user: 'root',
                        password: '',
                        admin_account: 'admin',
                        admin_password: '',
                    },
                    loadingState: {
                        install: false,
                    },
                    dbStatus: -1,
                    dataOfLog: [],
                    installStep: 0,
                }
            },
            methods: {
                initView() {
                    // 移除骨架屏
                    document.querySelectorAll('.skeleton').forEach(el => {
                        el.classList.remove("skeleton");
                    })
                },
                // 分步安装
                async installByStep() {
                    if (this.installStep == this.dataOfLog.length) {
                        this.loadingState.install = false;
                        // 安装补丁
                        this.installByPath();
                        return;
                    }
                    // 分步安装
                    let param = { ...this.dbcfg };
                    param.step = this.installStep;
                    let result = await axios({
                        url: 'api/api.php?action=install_db',
                        method: 'POST',
                        data: param,
                        headers: { 'Cache-Control': 'no-cache' }, // 禁用缓存
                    })
                    let stepSrv = result.data.data.step;
                    if (!result.data.status) {
                        // alert(result.data.message);
                        console.log('===', this.dataOfLog[result.data.data]);
                        this.dataOfLog[stepSrv].status = 2;
                        this.dataOfLog[stepSrv].error = result.data.message + "\n[SQL]: " + result.data.data.sql;
                        return;
                    }
                    this.dataOfLog[stepSrv].status = 1;
                    this.dataOfLog[stepSrv].error = '';
                    this.installStep++;
                    this.installByStep()
                },
                // 立即安装（安装预览）
                async onInstall() {
                    if (this.loadingState.install) {
                        alert('正在执行中，请勿重复操作！');
                        return;
                    }
                    this.loadingState.install = true;
                    window.sessionStorage.setItem("dbcfg", JSON.stringify(this.dbcfg));
                    let result = await axios({
                        url: 'api/api.php?action=install_preview',
                        method: 'POST',
                        data: this.dbcfg,
                        headers: { 'Cache-Control': 'no-cache' }, // 禁用缓存
                    })
                    console.log('result=', result);
                    if (!result.data.status) {
                        alert(result.data.message);
                        return;
                    }
                    this.dataOfLog = result.data.data;
                    this.installByStep();
                    // location.href = "finish.html"
                },
                // 安装补丁
                async installByPath() {
                    let param = { ...this.dbcfg };
                    // 安装补丁
                    param.step = 'patch';
                    let result = await axios({
                        url: 'api/api.php?action=install_patch',
                        method: 'POST',
                        data: param,
                        headers: { 'Cache-Control': 'no-cache' }, // 禁用缓存
                    })
                    if (!result.data.status) {
                        alert(result.data.message);
                        return;
                    }
                    location.href = "finish.html"
                },
                // 测试连接
                async onTestConnection() {
                    const result = await axios({
                        url: 'api/api.php?action=test_connection',
                        method: 'POST',
                        data: this.dbcfg,
                        headers: { 'Cache-Control': 'no-cache' }, // 禁用缓存
                    })
                    if (!result.data.status) {
                        alert(result.data.message);
                        return;
                    }
                    alert('连接成功');
                },
                // 检测数据库是否存在
                async checkDbExists() {
                    const result = await axios({
                        url: 'api/api.php?action=check_db',
                        method: 'POST',
                        data: this.dbcfg,
                        headers: { 'Cache-Control': 'no-cache' }, // 禁用缓存
                    })
                    if (!result.data.status) {
                        alert(result.data.message);
                        return;
                    }
                    this.dbStatus = result.data.data;
                },
                // 创建数据库
                async onCreateDatabase() {
                    const result = await axios({
                        url: 'api/api.php?action=create_db',
                        method: 'POST',
                        data: this.dbcfg,
                        headers: { 'Cache-Control': 'no-cache' }, // 禁用缓存
                    })
                    if (!result.data.status) {
                        alert(result.data.message);
                        return;
                    }
                    alert('数据库创建成功');
                }
            },
            mounted() {
                this.initView();
            }
        }
        // 创建应用实例
        const app = Vue.createApp(App)
        const vm = app.mount('#app')
    </script>
</body>

</html>